package com.slashmanx.helpers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.slashmanx.socialwall.SocialPicture;

import android.os.Environment;
import android.util.Log;

public class Downloader {

    public static String DownloadFile(SocialPicture p) {
        try {
	            //File root = Environment.getExternalStorageDirectory();
	        	  File sdCard = Environment.getExternalStorageDirectory();
	              File dir = new File (sdCard.getAbsolutePath() + "/SocialWall/Pictures");
	              dir.mkdirs();
	              File file = new File(dir, p.getName());
	              if(file.exists())
	              {
	            	  return null;
	              }
	              String fileLocation = file.getAbsolutePath();
	              Log.d("HFREWGWE", "loc: "+ fileLocation);
        	
	            URL u = new URL(p.getUrl());
	            Log.d("SOCIALWALL", "here");
	            HttpURLConnection c = (HttpURLConnection) u.openConnection();
	            c.addRequestProperty("User-Agent","Mozilla/5.0 (compatible)");
	            c.addRequestProperty("Accept","image/jpg");
	            c.setRequestMethod("GET");
	            c.setDoOutput(false);
	            
	            c.connect();
	           // FileOutputStream f = new FileOutputStream(new File(root, fileName));
	
	
	            FileOutputStream f = new FileOutputStream(file);
	
	            InputStream in = c.getInputStream();
	
	            byte[] buffer = new byte[1024];
	            int len1 = 0;
	            
	            while ((len1 = in.read(buffer)) > 0) {
	                f.write(buffer, 0, len1);
	            }
	            
	            f.close();
	            Log.d("IN HERE", "Returning: "+ fileLocation);
	            return fileLocation;
            
        } catch (Exception e) {
            Log.e("Downloader EXCEPTION", e.toString());
        }
		return null;

    }
}

